package sklepik.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class NetworkUtil {

	public File downloadFileToDisk(String url, File destinationDirectory, String fileName) throws IOException {
		
		File file = new File(destinationDirectory, fileName);
		URL u = new URL(fixWhitespace(url));
		URLConnection uc = u.openConnection();
		uc.connect();
		InputStream in = uc.getInputStream();
		FileOutputStream out = new FileOutputStream(file);
		final int BUF_SIZE = 1 << 8;
		byte[] buffer = new byte[BUF_SIZE];
		int bytesRead = -1;
		while ((bytesRead = in.read(buffer)) > -1) {
			out.write(buffer, 0, bytesRead);
		}
		in.close();
		out.close();
		return file;
	}

	private String fixWhitespace(String url) {
		return url.replaceAll(" ", "%20");
	}
}
